package kr.pe.johnkim.chattingday.mobile.util;

import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Google GCM 을 이용해서 Mobile Device 로 Message 를 발송하는 클래스 이다.
 *
 * gcm-server.jar, json_simple-1.1.jar 가 필요 하다.
 *
 * @author : johnkim <cale9797@gmail.com / Bettersoft Inc,.>
 * @Date : 12. 7. 4
 */
public class ChattingDayGCM {

    // SLF4J logging
    private Logger logger = LoggerFactory.getLogger(ChattingDayGCM.class);

    // API Key 
    private String googleGCMAPIKey;

    private String sessionInterval;
    private String passwordActivateInterval;

    /**
     * Mobile Device 로 message 를 발송 한다.
     * 
     * @param registrationId
     * @param messageContents
     * @throws IOException
     */
    public void sendMessage(String registrationId, String messageContents) throws IOException {
        logger.info("sendMessage");

        logger.info("API Key : {}", this.getGoogleGCMAPIKey());

        Sender sender = new Sender(this.getGoogleGCMAPIKey());
        Message message = new Message.Builder().addData("MESSAGE", messageContents).build();
        Result result = sender.send(message, registrationId, 2);

        logger.info("message : {}", message.getData());

        if(result.getMessageId() != null) {
            String canonicalRegId = result.getCanonicalRegistrationId();

//            logger.info("canonicalRegId : {}", canonicalRegId);

            if(canonicalRegId != null) {
                //
            }
        } else {
            String error = result.getErrorCodeName();

//            logger.info("error : {}", error);

            if(error.equals(Constants.ERROR_NOT_REGISTERED)) {
                //
            }
        }

        logger.info("sessionInterval          : {}", this.getSessionInterval());
        logger.info("passwordActivateInterval : {}", this.getPasswordActivateInterval());
    }

    /*
        API Key Setter Injection
     */

    public String getGoogleGCMAPIKey() {
        return googleGCMAPIKey;
    }

    public void setGoogleGCMAPIKey(String googleGCMAPIKey) {
        this.googleGCMAPIKey = googleGCMAPIKey;
    }

    public String getSessionInterval() {
        return sessionInterval;
    }

    public void setSessionInterval(String sessionInterval) {
        this.sessionInterval = sessionInterval;
    }

    public String getPasswordActivateInterval() {
        return passwordActivateInterval;
    }

    public void setPasswordActivateInterval(String passwordActivateInterval) {
        this.passwordActivateInterval = passwordActivateInterval;
    }
}
